package it.fuesi.synoutils.adapters;

import android.app.Fragment;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;

import it.fuesi.synoutils.R;
import it.fuesi.synoutils.helpers.FormatHelper;
import it.fuesi.synoutils.model.download.DownloadStationClientParameters;
import it.fuesi.synoutils.model.download.DownloadTask;
import it.fuesi.synoutils.model.download.DownloadTasksListDataObject;
import it.fuesi.synoutils.model.download.TaskTransfer;
import it.fuesi.synoutils.services.tasks.download.DownloadTaskList;

/**
 * Created by pascotto on 16/10/14.
 */
public class DownloadTasksAdapter extends SynoAdapter<DownloadTasksListDataObject>{

        protected static final String TAG = "DownloadTasksAdapter";

        protected List<DownloadTask> data;
        private Context context;
        private Fragment fragment;
        private LayoutInflater inflater;

        private int total;
        private int completed;
        private int pending;

        public int getTotal() {
            return total;
        }

        public int getCompleted(){
            return completed;
        }

        public int getPending(){
            return pending;
        }

        public TaskTransfer info;

        public TaskTransfer getInfo(){
            return this.info;
        }


        @Override
        public Context getContext(){
            return this.context;
        }

        public DownloadTasksAdapter(LayoutInflater inflater, List<DownloadTask> data, Context context, Fragment fragment)  {
            this.data = data;
            this.context=context;
            this.fragment=fragment;
            this.inflater = inflater;
        }


        private List<DownloadTask> reorder(List<DownloadTask> tasks){
            total = 0;
            completed = 0;
            pending = 0;
            if(tasks == null) return tasks;


            final TreeMap<Integer, List<DownloadTask>> map = new TreeMap<Integer, List<DownloadTask>>();

            int currentPerc = 100;

            for(DownloadTask task : tasks){
                if(task.getTaskStatus() == DownloadTask.TaskStatus.finished) completed ++;

                final List<DownloadTask> curList;

                if(map.containsKey(task.getDownloadPercent()))
                    curList = map.get(task.getDownloadPercent());
                else
                    curList = new LinkedList<DownloadTask>();

                curList.add(task);

                map.put(task.getDownloadPercent(), curList);

                total++;
            }

            pending = total - completed;


            final List<DownloadTask> list = new ArrayList<DownloadTask>();
            for(List<DownloadTask> curList : map.descendingMap().values()){
                for(DownloadTask task : curList)
                    list.add(task);
            }

            return list;
        }




        @Override
        public void setItemCollection(DownloadTasksListDataObject data){
            this.data = reorder(data.getTasks());
            this.info = data.getInfo();
            notifyDataSetChanged();
        }

        /* (non-Javadoc)
         * @see android.widget.Adapter#getCount()
         */
        @Override
        public int getCount() {
            return data != null ? data.size() : 0;
        }

        /* (non-Javadoc)
         * @see android.widget.Adapter#getItem(int)
         */
        @Override
        public Object getItem(int index) {
            if(data != null && data.size() > index) {
                return data.get(index);
            }
            return null;
        }

        /* (non-Javadoc)
         * @see android.widget.Adapter#getItemId(int)
         */
        @Override
        public long getItemId(int id) {
            return id;
        }

        /* (non-Javadoc)
         * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View vi=convertView;
            if(convertView==null){
                vi = inflater.inflate(R.layout.download_task_item, null);
            }

            if(position%2 == 0)
                vi.setBackgroundColor(getContext().getResources().getColor(android.R.color.holo_blue_bright));
            else
                vi.setBackgroundColor(getContext().getResources().getColor(android.R.color.holo_blue_light));


            final DownloadTask task = data.get(position);

            Log.d(TAG, "getView --> displaying item: " + position);


            final View finalView = vi;

            TextView mTaskTitle = (TextView)vi.findViewById(R.id.task_title);

            TextView mTaskStatus = (TextView)vi.findViewById(R.id.task_status);

            TextView mTaskSize = (TextView)vi.findViewById(R.id.task_size);

            TextView mTaskDownloadSpeed = (TextView)vi.findViewById(R.id.task_download_speed);

            ProgressBar mTaskProgress = (ProgressBar)vi.findViewById(R.id.task_progress);

            ImageView mType = (ImageView)vi.findViewById(R.id.task_type);
            if(task.getType() != null && task.getType().equals("emule")){
                mType.setImageDrawable(context.getResources().getDrawable(R.drawable.icon_emule));
            }else
                mType.setImageDrawable(context.getResources().getDrawable(R.drawable.icon_bt));

            long size = task.getSize();

            long downloaded = task.getAdditional().getTransfer().getSize_downloaded();

            mTaskProgress.setMax(100);

            mTaskProgress.setProgress(task.getDownloadPercent());

            mTaskTitle.setText(task.getTitle());

            mTaskStatus.setText(task.getStatus());

            mTaskSize.setText(FormatHelper.formatFileSize(downloaded) + " / " + FormatHelper.formatFileSize(size));

            mTaskDownloadSpeed.setText(FormatHelper.formatSpeed(task.getAdditional().getTransfer().getSpeed_download()));


            return finalView;
        }


        public void fetch(){
            fetch(null);
        }

        public void fetch(DownloadStationClientParameters params){
            new DownloadTaskList(this).execute(params);
        }

        public List<DownloadTask> getCompletedTasks(){
            final List<DownloadTask> list = new LinkedList<DownloadTask>();
            if(this.data != null){
                for (DownloadTask task : data){
                    if(task.getStatus().equals(DownloadTask.TaskStatus.finished.toString()))
                        list.add(task);
                }
            }

            return list;
        }







}
